package com.metal.gear.certification.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.metal.gear.common.entity.Result;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import javax.sql.DataSource;
import java.io.PrintWriter;

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Resource
    @Lazy
    UserDetailsService userDetailsService;

    @Resource
    DataSource dataSource;

    @Resource
    ObjectMapper objectMapper;


//    @Bean
//    public PersistentTokenRepository persistentTokenRepository() {
//        JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
//        jdbcTokenRepository.setDataSource(dataSource);
//        //jdbcTokenRepository.setCreateTableOnStartup(true);
//        return jdbcTokenRepository;
//    }
//
//    @Bean
//    public PersistentTokenBasedRememberMeServices persistentTokenBasedRememberMeServices() {
//        PersistentTokenBasedRememberMeServices persistentTokenBasedRememberMeServices
//                = new PersistentTokenBasedRememberMeServices("lijiexi", userDetailsService, persistentTokenRepository());
//        persistentTokenBasedRememberMeServices.setAlwaysRemember(false);
//        return persistentTokenBasedRememberMeServices;
//    }


    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    protected SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.formLogin()
                .loginProcessingUrl("/sys/authentication/doLogin")
                .successHandler(authenticationSuccessHandler())
                .failureHandler(authenticationFailureHandler());
        http.logout().logoutUrl("/sys/authentication/logout");
        http.authorizeHttpRequests()
                .requestMatchers("/doc.html","/swagger-ui/**", "/v3/api-docs/**", "/webjars/**", "/img.icons/**","/sys/authentication/doLogin").permitAll()
                .anyRequest().authenticated();

        http.exceptionHandling().authenticationEntryPoint(unAuthenticationJsonEntryPoint());

        http.csrf().disable();
        return http.build();
    }

    /***
     *
     * @return
     */
    private AuthenticationSuccessHandler authenticationSuccessHandler() {
        return (request, response, authentication) -> {
            response.setContentType("application/json;charset=utf-8");
            Result<String> result = new Result<>(200, "身份验证成功！");
            String s = objectMapper.writeValueAsString(result);
            PrintWriter writer = response.getWriter();
            writer.write(s);
            writer.flush();
            writer.close();
        };
    }

    /***
     * todo 待补充
     *
     * @return AuthenticationFailureHandler 认证失败的
     */
    private AuthenticationFailureHandler authenticationFailureHandler() {
        return (request, response, exception) -> {
            response.setContentType("application/json;charset=utf-8");
            Result<String> result = new Result<>(500, "身份验证失败！");
            String s = objectMapper.writeValueAsString(result);
            PrintWriter writer = response.getWriter();
            writer.write(s);
            writer.flush();
            writer.close();
        };
    }

    private AuthenticationEntryPoint unAuthenticationJsonEntryPoint() {
        return (request, response, authException) -> {
            response.setContentType("application/json;charset=utf-8");
            Result<String> result = new Result<>(500, "未进行身份验证！");
            String s = objectMapper.writeValueAsString(result);
            PrintWriter out = response.getWriter();
            out.write(s);
            out.flush();
            out.close();
        };
    }
}
